// 全局状态机：地图保存全局对象
import Vue from 'vue'
// 初始状态
const state = {
  // 地图对象
  mapObj: {},
  // 更新地图定时器的id
  updateMapSizeIntervalId: null,
  // 底图图层
  baseMapLayers: [],

  points: [],

  pointsId: null
}

// getters
const getters = {
  // 执行时返回函数，函数接受id作为参数
  getMapObj: state => {
    return state.mapObj
  },
  // 获取底图数组
  getBaseMapLayers: state => {
    return state.baseMapLayers
  },
  getPoints: state => {
    return state.points
  }
}

// 异步操作
const actions = {
  setMapObj: function ({ commit, state }, option) {
    // 设置地图对象
    commit('setMapObj', option)
    // 开启地图尺寸重新计算定时任务
    commit('setUpdateMapSizeIntervalId', null)
  },
  // 显示指定图层
  mapUpdateSize: function ({ commit, state }, option) {
    // 提交修改数据
    commit('mapUpdateSize', option)
  },
  // 切换视角
  setView: function ({ commit, state }, viewObj) {
    // 提交修改数据
    state.mapObj.getView().animate(viewObj)
  },
  addInteraction ({ commit, state }, viewObj) {
    commit('addInteraction', viewObj)
  },
  // 添加事件监听
  addMapEventListener ({ commit, state }, listener) {
    commit('addMapEventListener', listener)
  },
  // 地图缩放控制，调用一次增加一级或减少一级
  changeMapZoom ({ commit, state }, isAdd) {
    var view = state.mapObj.getView()
    var zoom = view.getZoom()
    if (isAdd) {
      // view.setZoom(zoom + 1)
      view.animate({
        zoom: zoom + 1,
        duration: 700
      })
    } else {
      view.animate({
        zoom: zoom - 1,
        duration: 700
      })
    }
  },
  // 初始化底图
  initBaseMapLayers ({ commit, state }, baseMapLayers) {
    commit('initBaseMapLayers', baseMapLayers)
  },
  initPoints ({ commit, state }, points) {
    commit('initPoints', points)
  }
}

// 提交操作
const mutations = {
  initPoints: function (state, points) {
    state.points = points
  },
  initBaseMapLayers: function (state, baseMapLayers) {
    state.baseMapLayers = baseMapLayers
  },
  setMapObj: function (state, mapObj) {
    Vue.set(state, 'mapObj', mapObj)
  },
  // 地图尺寸重新计算
  mapUpdateSize: function (state, payload) {
    state.mapObj.updateSize()
  },
  // 设置定时器
  setUpdateMapSizeIntervalId: function (state, payload) {
    if (state.updateMapSizeIntervalId != null) {
      clearInterval(state.updateMapSizeIntervalId)
    }
    state.updateMapSizeIntervalId = setInterval(function () {
      state.mapObj.updateSize()
    }, 1000)
  },
  setPointsId: function (state, pointsId) {
    if (state.pointsId != null) {
      clearInterval(state.pointsId)
    }
  },
  addInteraction: function (state, payload) {
    state.mapObj.addInteraction(payload)
  },
  // 添加事件监听
  addMapEventListener (state, {name, fun}) {
    state.mapObj.on(name, fun)
  }
}
// 导出
export default {
  state,
  getters,
  actions,
  mutations
}
